# -*- coding: utf-8 -*-
from core.resources import CustomerModelResource
from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget
from apps.sys.models import DictData, User
from apps.sys.dict.widgets import DictDataLabelWidget
from .models import Product


class ImportProductResources(CustomerModelResource):
    auto_import_headers = False

    name = Field(attribute="name", column_name="产品名称")
    number = Field(attribute="number", column_name="产品编号")
    type = Field(
        attribute="type",
        column_name="产品类型",
        widget=DictDataLabelWidget(dict_type="pms_product_type"),
    )
    status = Field(
        attribute="status",
        column_name="产品状态",
        widget=DictDataLabelWidget(dict_type="sys_enable_disable"),
    )
    owner = Field(
        column_name="负责人",
        attribute="owner",
        widget=ForeignKeyWidget(User, field="username"),
    )
    remark = Field(attribute="remark", column_name="备注")

    class Meta:
        model = Product
        import_id_fields = ("number",)


class ExportProductResources(CustomerModelResource):
    name = Field(attribute="name", column_name="产品名称")
    number = Field(attribute="number", column_name="产品编号")
    type = Field(column_name="产品类型")
    status = Field(column_name="产品状态")
    owner = Field(attribute="owner__username", column_name="负责人")
    remark = Field(attribute="remark", column_name="备注")

    class Meta:
        model = Product
        fields = [
            "name",
            "number",
            "type",
            "status",
            "owner",
            "remark",
        ]

    def dehydrate_type(self, instance):
        return DictData.objects.get(type="pms_product_type", value=instance.type).label

    def dehydrate_status(self, instance):
        return DictData.objects.get(
            type="sys_enable_disable", value=instance.status
        ).label
